 package com.zhiche.lisa.integration.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.google.common.collect.Lists;
import com.zhiche.lisa.core.enums.IntegrationURIEnum;
import com.zhiche.lisa.core.enums.SystemEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.core.utils.redislog.RedisLogUtil;
import com.zhiche.lisa.integration.config.IntegrationProperties;
import com.zhiche.lisa.integration.dao.model.ImportLogHistory;
import com.zhiche.lisa.integration.dao.model.PushSubSystem;
import com.zhiche.lisa.integration.dto.huiyunche.*;
import com.zhiche.lisa.integration.service.IHuiyuncheService;
import com.zhiche.lisa.integration.service.IImportLogHistoryService;
import com.zhiche.lisa.integration.service.IImportLogService;
import com.zhiche.lisa.integration.service.IPushSubSystemService;
import com.zhiche.lisa.integration.surpports.enums.TableStatusEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class HuiyuncheServiceImpl implements IHuiyuncheService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private IPushSubSystemService systemService;
    @Autowired
    private IImportLogService logService;
    @Autowired
    private IntegrationProperties properties;

    @Value("${hyc.url}")
    private String hycUrl;

    @Value("${hyc.getOrders}")
    private String getOrders;

    @Value("${hyc.socketTimeout}")
    private Integer socketTimeout;

    @Value("${hyc.getOrderDetail}")
    private String getOrderDetail;

    @Value("${newHyc.url}")
    private String newHycUrl;

    @Value("${newHyc.getNewOrders}")
    private String getNewOrders;

    @Value("${newHyc.getNewOrderDetail}")
    private String getNewOrderDetail;

    @Value("${logRedis.isTest}")
    private boolean isTest;

    @Autowired
    private IImportLogHistoryService importLogHistoryService;
    /**
     * 导入人送指令
     */
    @Override
    public void importShipment(HuiyuncheShipInfoDTO shipInfo) {
        String dtoJson = JSONObject.toJSONString(shipInfo);
        logger.info("/huiyuncheInterface/importShipment ---人送指令param:{}", dtoJson);
        Wrapper<PushSubSystem> ew = new EntityWrapper<>();
        ew.eq("type", TableStatusEnum.STATUS_11.getCode());
        List<PushSubSystem> subSystems = systemService.selectList(ew);
        //推送日志记录
        ImportLogHistory importLogHistory = new ImportLogHistory();
        importLogHistory.setSourceSys("huiyunche");
        importLogHistory.setTargetSys("TMS");
        importLogHistory.setSourceKey(shipInfo.getVcorderno());
        importLogHistory.setType(TableStatusEnum.STATUS_11.getCode());
        importLogHistory.setImportStartTime(new Date());
        importLogHistory.setImportEndTime(new Date());
        new Thread(() -> {
            logger.info("开始保存导入日志---------------");
            try {
                logService.saveImportLogToQiniu(importLogHistory, dtoJson);
                logger.info("完成人送指令推送日志保存---------------");
            } catch (Exception e) {
                logger.error("人送指令推送日志保存失败---------------");
            }
        }).start();

        //oms
        if (CollectionUtils.isNotEmpty(subSystems)) {
            for (PushSubSystem subSys : subSystems) {
//                //推送OMS 前获取token
//                String token = null;
//                if (TableStatusEnum.STATUS_1.getCode().equals(subSys.getRemarks())) {
//                    ArrayList<NameValuePair> headers = Lists.newArrayList();
//                    headers.add(new BasicNameValuePair("Authorization", TableStatusEnum.STATUS_1.getCode()));
//                    ArrayList<NameValuePair> params = Lists.newArrayList();
//                    params.add(new BasicNameValuePair("mobile", shipInfo.getDriverPhone()));
//                    ArrayList<NameValuePair> tmsHeader = Lists.newArrayList();
//                    String url = properties.getUaaHost() + IntegrationURIEnum.UAA_GET_TOKEN_DRIVER_MOBILE.getAddress();
//                    try {
//                        logger.info("人送指令-->连接uaa获取token url:{},param:{}", url, JSON.toJSONString(params));
//                        String res = HttpClientUtil.get(url,
//                                headers, params, properties.getSocketTimeout());
//                        logger.info("人送指令-->连接uaa获取token url:{},token:{}", url, res);
//                        if (!StringUtils.isEmpty(res)) {
//                            token = JSONObject.parseObject(res).getString("data");
//                        }
//                    } catch (Exception e) {
//                        logger.error("人送指令-->连接uaa url:{}--->获取token失败,参数:{}", url, JSONObject.toJSONString(params));
//                    }
//                    if (!StringUtils.isEmpty(token)) {
//                        tmsHeader.add(new BasicNameValuePair("Authorization", token));
//                    }
                    String result = null;
                    try {
                        logger.info("人送指令-->指令推送子系统：{}，地址：{}，开始！参数：{}", subSys.getCode(), subSys.getUrl(), dtoJson);
                        //推送子系统(tms)
                        result = HttpClientUtil.postJson(subSys.getUrl(),
                                null,
                                dtoJson,
                                subSys.getSocketTimeOut());
                        logger.info("人送指令-->指令推送子系统：{},地址:{},成功！result:{}", subSys.getCode(), subSys.getUrl(), result);
                        parseRsult(importLogHistory,result);
                    } catch (Exception e) {
                        importLogHistory.setImportStatus("error");
                        importLogHistory.setImportNote(null == e.getMessage()?null : e.getMessage());
                        logger.error("人送指令-->指令推送子系统：{},地址:{},失败！原因:{},参数:{}", subSys.getCode(), subSys.getUrl(), e, dtoJson);
                    }
                importLogHistoryService.updateById(importLogHistory);
           //     }

                //记录指令已接收到日志系统
                RedisLogUtil.addSysShipmentLogs(SystemEnum.INTEGRATION.getCode(), SystemEnum.OMS.getCode(), "/omsHuiyunche/shipInfo", shipInfo.getVcorderno(),
                        null, JSONObject.toJSONString(shipInfo), 1, 1, "", isTest);
            }
        }
    }

    /**
     * 人送退单下发运力平台/otm
     */
    @Override
    public void cancelShip(HuiyuncheCommonDTO dto) {
        String dtoJson = JSONObject.toJSONString(dto);
        logger.info("/huiyuncheInterface/cancelShip ---人送指令取消param:{}", dtoJson);
        Wrapper<PushSubSystem> ew = new EntityWrapper<>();
        ew.eq("type", TableStatusEnum.STATUS_12.getCode());
        List<PushSubSystem> subSystems = systemService.selectList(ew);
        //推送日志记录
        ImportLogHistory importLogHistory = new ImportLogHistory();
        importLogHistory.setSourceSys("huiyunche");
        importLogHistory.setTargetSys("TMS");
        importLogHistory.setSourceKey(dto.getOrderCode());
        importLogHistory.setType(TableStatusEnum.STATUS_12.getCode());
        importLogHistory.setImportStartTime(new Date());
        importLogHistory.setImportEndTime(new Date());
       // new Thread(() -> {
            logger.info("人送退单-->开始保存导入日志---");
            try {
                logService.saveImportLogToQiniu(importLogHistory, dtoJson);
                logger.info("人送退单-->日志保存成功---------------");
            } catch (Exception e) {
                logger.error("人送退单-->日志保存失败---------------");
            }
       // }).start();
        //oms
        if (CollectionUtils.isNotEmpty(subSystems)) {
            for (PushSubSystem subSys : subSystems) {
//                //推送OMS 前获取token
//                String token = null;
//                if (TableStatusEnum.STATUS_1.getCode().equals(subSys.getRemarks())) {
//                    ArrayList<NameValuePair> headers = Lists.newArrayList();
//                    headers.add(new BasicNameValuePair("Authorization", TableStatusEnum.STATUS_1.getCode()));
//                    ArrayList<NameValuePair> params = Lists.newArrayList();
//                    params.add(new BasicNameValuePair("mobile", dto.getPhone()));
//                    String url = properties.getUaaHost() + IntegrationURIEnum.UAA_GET_TOKEN_DRIVER_MOBILE.getAddress();
//                    try {
//                        logger.info("人送退单-->连接uaa获取token url:{},param:{}", url, JSON.toJSONString(params));
//                        String res = HttpClientUtil.get(url,
//                                headers, params, properties.getSocketTimeout());
//                        logger.info("人送退单-->连接uaa获取token url:{},token:{}", url, res);
//                        if (!StringUtils.isEmpty(res)) {
//                            token = JSONObject.parseObject(res).getString("data");
//                        }
//                    } catch (Exception e) {
//                        logger.error("人送退单-->连接uaa url:{}--->获取token失败,参数:{}", url, JSONObject.toJSONString(params));
//                    }
//                    ArrayList<NameValuePair> tmsHeader = Lists.newArrayList();
//                    if (!StringUtils.isEmpty(token)) {
//                        tmsHeader.add(new BasicNameValuePair("Authorization", token));
//                    }
                    String result = null;
                    try {
                        logger.info("人送退单-->推送子系统：{}，地址：{}，开始！参数：{}", subSys.getCode(), subSys.getUrl(), dtoJson);

                        //系统交互下发日志记录
                        RedisLogUtil.addSysLogs(SystemEnum.INTEGRATION.getCode(), SystemEnum.OMS.getCode(), dto.getOrderCode(), dtoJson,
                                "/omsHuiyunche/cancelShip", 1, 1, "", isTest);

                        //推送子系统(tms)
                        result = HttpClientUtil.postJson(subSys.getUrl(),
                                null,
                                dtoJson,
                                subSys.getSocketTimeOut());
                        logger.info("人送退单-->推送子系统：{}，地址：{}，成功！返回结果：{}", subSys.getCode(), subSys.getUrl(),result);
                        parseRsult(importLogHistory,result);
                    } catch (Exception e) {
                        logger.error("人送退单-->推送子系统：{}，地址：{}，失败！原因：{},参数：{}", subSys.getCode(), subSys.getUrl(), e, dtoJson);
                        importLogHistory.setImportStatus("error");
                        importLogHistory.setImportNote(null == e.getMessage()?null : e.getMessage());
                    }
                importLogHistoryService.updateById(importLogHistory);
              //  }
            }
        }
    }

    /**
     * 人送订单发运传送lspm
     */
    @Override
    public void shipConfirm(HuiyuncheCommonDTO dto) {
        String dtoJson = JSONObject.toJSONString(dto);
        logger.info("/huiyuncheInterface/shipConfirm ---人送指令发运:{}", dtoJson);
        Wrapper<PushSubSystem> ew = new EntityWrapper<>();
        ew.eq("type", TableStatusEnum.STATUS_31.getCode());
        List<PushSubSystem> subSystems = systemService.selectList(ew);
        //推送日志记录
        ImportLogHistory importLogHistory = new ImportLogHistory();
        importLogHistory.setSourceSys("huiyunche");
        importLogHistory.setTargetSys("TMS");
        importLogHistory.setSourceKey(dto.getOrderCode());
        importLogHistory.setType(TableStatusEnum.STATUS_31.getCode());
        importLogHistory.setImportStartTime(new Date());
        importLogHistory.setImportEndTime(new Date());
        //new Thread(() -> {
            logger.info("人送发运-->开始保存导入日志----------");
            try {
                logService.saveImportLogToQiniu(importLogHistory, dtoJson);
                logger.info("人送发运-->完成人送指令推送日志保存-------");
            } catch (Exception e) {
                logger.error("人送发运-->人送指令推送日志保存失败------");
            }
       //}).start();
        if (CollectionUtils.isNotEmpty(subSystems)) {
            for (PushSubSystem subSys : subSystems) {
                //推送OMS 前获取token
                String token = null;
                if (TableStatusEnum.STATUS_1.getCode().equals(subSys.getRemarks())) {
//                    ArrayList<NameValuePair> headers = Lists.newArrayList();
//                    headers.add(new BasicNameValuePair("Authorization", TableStatusEnum.STATUS_1.getCode()));
//                    ArrayList<NameValuePair> params = Lists.newArrayList();
//                    params.add(new BasicNameValuePair("mobile", dto.getPhone()));
//                    String url = properties.getUaaHost() + IntegrationURIEnum.UAA_GET_TOKEN_DRIVER_MOBILE.getAddress();
//                    try {
//                        logger.info("人送发运-->连接uaa获取token url:{},param:{}", url, JSON.toJSONString(params));
//                        String res = HttpClientUtil.get(url,
//                                headers, params, properties.getSocketTimeout());
//                        logger.info("人送发运-->连接uaa获取token url:{},token:{}", url, res);
//                        if (!StringUtils.isEmpty(res)) {
//                            token = JSONObject.parseObject(res).getString("data");
//                        }
//                    } catch (Exception e) {
//                        logger.error("人送发运-->连接uaa url:{}--->获取token失败,参数:{}", url, JSONObject.toJSONString(params));
//                    }
//                    ArrayList<NameValuePair> tmsHeader = Lists.newArrayList();
//                    if (!StringUtils.isEmpty(token)) {
//                        tmsHeader.add(new BasicNameValuePair("Authorization", token));
//                    }
                    String result = null;
                    try {
                        logger.info("人送发运-->推送子系统：{}，地址：{}，开始！参数：{}", subSys.getCode(), subSys.getUrl(), dtoJson);

                        //系统交互下发日志记录
                        RedisLogUtil.addSysLogs(SystemEnum.INTEGRATION.getCode(), SystemEnum.OMS.getCode(), dto.getOrderCode(), dtoJson,
                                "/ship/peopleSendDepartureConfirmation", 1, 1, "", isTest);

                        //推送子系统(tms)
                        result = HttpClientUtil.postJson(subSys.getUrl(),
                                null,
                                dtoJson,
                                subSys.getSocketTimeOut());
                        logger.info("人送发运-->推送子系统：{}，地址：{}，成功！返回结果：{}", subSys.getCode(), subSys.getUrl(),result);
                        parseRsult(importLogHistory,result);
                    } catch (Exception e) {
                        logger.error("人送发运-->推送子系统：{}，地址：{}，失败！原因：{},参数：{}", subSys.getCode(), subSys.getUrl(), e, dtoJson);
                        importLogHistory.setImportStatus("error");
                        importLogHistory.setImportNote(null == e.getMessage()?null : e.getMessage());
                    }
                    importLogHistoryService.updateById(importLogHistory);
                }
            }
        }
    }

    @Override
    public void shipTo(HuiyuncheCommonDTO dto) {
        String dtoJson = JSONObject.toJSONString(dto);
        logger.info("/huiyuncheInterface/shipTo ---人送指令运抵:{}", dtoJson);
        Wrapper<PushSubSystem> ew = new EntityWrapper<>();
        ew.eq("type", TableStatusEnum.STATUS_32.getCode());
        List<PushSubSystem> subSystems = systemService.selectList(ew);
        //推送日志记录
        ImportLogHistory importLogHistory = new ImportLogHistory();
        importLogHistory.setSourceSys("huiyunche");
        importLogHistory.setTargetSys("TMS");
        importLogHistory.setSourceKey(dto.getOrderCode());
        importLogHistory.setType(TableStatusEnum.STATUS_32.getCode());
        importLogHistory.setImportStartTime(new Date());
        importLogHistory.setImportEndTime(new Date());
        // new Thread(() -> {
            logger.info("人送运抵-->开始保存导入日志----------");
            try {
                logService.saveImportLogToQiniu(importLogHistory, dtoJson);
                logger.info("人送运抵-->完成人送指令推送日志保存-------");
            } catch (Exception e) {
                logger.error("人送运抵-->人送指令推送日志保存失败------");
            }
        // }).start();
        if (CollectionUtils.isNotEmpty(subSystems)) {
            for (PushSubSystem subSys : subSystems) {
                //推送OMS 前获取token
                String token = null;
                if (TableStatusEnum.STATUS_1.getCode().equals(subSys.getRemarks())) {
//                    ArrayList<NameValuePair> headers = Lists.newArrayList();
//                    headers.add(new BasicNameValuePair("Authorization", TableStatusEnum.STATUS_1.getCode()));
//                    ArrayList<NameValuePair> params = Lists.newArrayList();
//                    params.add(new BasicNameValuePair("mobile", dto.getPhone()));
//                    String url = properties.getUaaHost() + IntegrationURIEnum.UAA_GET_TOKEN_DRIVER_MOBILE.getAddress();
//                    try {
//                        logger.info("人送运抵-->连接uaa获取token url:{},param:{}", url, JSON.toJSONString(params));
//                        String res = HttpClientUtil.get(url,
//                                headers, params, properties.getSocketTimeout());
//                        logger.info("人送运抵-->连接uaa获取token url:{},token:{}", url, res);
//                        if (!StringUtils.isEmpty(res)) {
//                            token = JSONObject.parseObject(res).getString("data");
//                        }
//                    } catch (Exception e) {
//                        logger.error("人送运抵-->连接uaa url:{}--->获取token失败,参数:{}", url, JSONObject.toJSONString(params));
//                    }
//                    ArrayList<NameValuePair> tmsHeader = Lists.newArrayList();
//                    if (!StringUtils.isEmpty(token)) {
//                        tmsHeader.add(new BasicNameValuePair("Authorization", token));
//                    }
                    String result = null;
                    try {
                        logger.info("人送运抵-->推送子系统：{}，地址：{}，开始！参数：{}", subSys.getCode(), subSys.getUrl(), dtoJson);

                        //系统交互下发日志记录
                        RedisLogUtil.addSysLogs(SystemEnum.INTEGRATION.getCode(), SystemEnum.OMS.getCode(), dto.getOrderCode(), dtoJson,
                                "/ship/peopleSendShippingTo", 1, 1, "", isTest);

                        //推送子系统(tms)
                        result = HttpClientUtil.postJson(subSys.getUrl(),
                                null,
                                dtoJson,
                                subSys.getSocketTimeOut());
                        logger.info("人送运抵-->推送子系统：{}，地址：{}，成功！返回结果：{}", subSys.getCode(), subSys.getUrl(),result);
                        parseRsult(importLogHistory,result);
                    } catch (Exception e) {
                        logger.error("人送运抵-->推送子系统：{}，地址：{}，失败！原因：{},参数：{}", subSys.getCode(), subSys.getUrl(), e, dtoJson);
                        importLogHistory.setImportStatus("error");
                        importLogHistory.setImportNote(null == e.getMessage()?null : e.getMessage());
                    }
                    importLogHistoryService.updateById(importLogHistory);
                }
            }
        }
    }

    private void  parseRsult(ImportLogHistory importLogHistory,String result){
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (StringUtils.isEmpty(result)){
            importLogHistory.setImportStatus("error");
            importLogHistory.setImportNote("无响应");
        }else if (jsonObject.getInteger("code")==0){
            importLogHistory.setImportStatus("success");
        }else if (jsonObject.getInteger("code")!=0){
            importLogHistory.setImportStatus("error");
            importLogHistory.setImportNote(jsonObject.getString("message"));
        }
    }
    /**
     * 获取定单号列表
     */
    @Override
    public void getOrderCodes(){
        //获取订单号列表；
        String result = HttpClientUtil.get(hycUrl + getOrders, null, socketTimeout);
        logger.info("二手车获取订单号列表 地址：{}，result：{}",hycUrl + getOrders,result);
        if (!StringUtils.isEmpty(result)){
            JSONObject jsonObject = JSONObject.parseObject(result);
            Boolean success = jsonObject.getBoolean("success");
            String data = jsonObject.getString("data");
            if (success){
                List<OrderCodeDTO> orderCodeDTOS = JSONObject.parseArray(data, OrderCodeDTO.class);
                for (OrderCodeDTO orderCodeDTO : orderCodeDTOS) {
                    //根据订单号获取明细
                    getOrderDetail(orderCodeDTO.getCode());
                }
            }else {
                throw new BaseException(jsonObject.getString("message"));
            }
        }

    }

    @Override
    public void getOrderDetail(String orderCode) {
        Map<String,String> params=new HashMap<>();
        params.put("orderCode",orderCode);
        String result = HttpClientUtil.post(hycUrl + getOrderDetail, null, params, socketTimeout);
        logger.info("二手车获取订单号明细 url：{}，result：{},param:{}",hycUrl + getOrderDetail,result,params);
        if (!StringUtils.isEmpty(result)){
            JSONObject jsonObject = JSONObject.parseObject(result);
            Boolean success = jsonObject.getBoolean("success");
            String data = jsonObject.getString("data");
            if (success){
                HuiyuncheUsedCarsDTO huiyuncheUsedCarsDTO = JSONObject.parseObject(data, HuiyuncheUsedCarsDTO.class);
                UsedCarToOtm usedCarToOtm = usedCarToOtm(huiyuncheUsedCarsDTO);
                JSONObject jsonData = new JSONObject();
                jsonData.put("orderQuery", usedCarToOtm);
                String dataToOtm = jsonData.toJSONString();
                Wrapper<PushSubSystem> ew = new EntityWrapper<>();
                ew.eq("type", IntegrationURIEnum.USED_CARS.getCode());
                PushSubSystem subSystems = systemService.selectOne(ew);
                String res = HttpClientUtil.postJsoneRturnError(subSystems.getUrl(), null, dataToOtm, socketTimeout);
                JSONObject parseObject = JSONObject.parseObject(res);
                logger.info("getOrderDetail to otm Url:{},result:{},otmParam:{}",subSystems.getUrl(),res,dataToOtm);
                Integer isSuc = 0;
                //导入日志
                ImportLogHistory importLogHistory = new ImportLogHistory();
                importLogHistory.setSourceSys("hyc");
                importLogHistory.setTargetSys("OTM");
                importLogHistory.setSourceKey(huiyuncheUsedCarsDTO.getOrderCode());
                importLogHistory.setType(com.zhiche.lisa.core.enums.TableStatusEnum.STATUS_HUIYUNCHE_USEDCAR.getCode());
                if ("200".equals(parseObject.getString("messageCode"))){
                    isSuc = 1;
                    importLogHistory.setImportStatus("success");
                }else{
                    isSuc = 0;
                    importLogHistory.setImportStatus("error");
                }
                importLogHistory.setImportNote(res);
                importLogHistory.setImportStartTime(new Date());
                importLogHistory.setImportEndTime(new Date());
                new Thread(() -> {
                    logger.info("开始保存导入日志---------------");
                    try {
                        logService.saveImportLogToQiniu(importLogHistory, dataToOtm);
                    } catch (Exception e) {
                        logger.error("日志保存失败---------------");
                    }
                    logger.info("完成日志保存---------------");
                }).start();

                //二手车推送otm 系统交互日志记录
                RedisLogUtil.addSysLogs(SystemEnum.INTEGRATION.getCode(), SystemEnum.OTM.getCode(), importLogHistory.getSourceKey(), importLogHistory.getDataStorageKey(),
                        "/zlzc/usedcar_order_interface", 1, isSuc, res,isTest);
            }else {
                throw new BaseException(jsonObject.getString("message"));
            }
        }
    }


    /**
     * 获取定单号列表
     */
    @Override
    public void getNewOrderCodes(){
        //获取订单号列表；
        String result = HttpClientUtil.get(newHycUrl + getNewOrders, null, socketTimeout);
        logger.info("新二手车获取订单号列表 地址：{}，result：{}",newHycUrl + getNewOrders,result);
        if (!StringUtils.isEmpty(result)){
            JSONObject jsonObject = JSONObject.parseObject(result);
            logger.info("新二手车获取订单号数据 data：{}",jsonObject);
            Integer code = jsonObject.getInteger("code");
            if (code==0){
                String data = jsonObject.getString("data");
                List<OrderCodeDTO> orderCodeDTOS = JSONObject.parseArray(data, OrderCodeDTO.class);
                for (OrderCodeDTO orderCodeDTO : orderCodeDTOS) {
                    //根据订单号获取明细
                    getNewOrderDetail(orderCodeDTO.getOrderCode());
                }
            }else {
                throw new BaseException(jsonObject.getString("message"));
            }
        }else {
            logger.info("新二手车获取订单号列表为空=="+result);
        }

    }

    @Override
    public void getNewOrderDetail(String orderCode) {
        List<NameValuePair> pramsNamePairs = Lists.newArrayList();
        pramsNamePairs.add(new BasicNameValuePair("orderCode", orderCode));
        String result = HttpClientUtil.get(newHycUrl + getNewOrderDetail, null, pramsNamePairs, socketTimeout);
        logger.info("新二手车获取订单号明细 url：{}，result：{},param:{}",newHycUrl + getNewOrderDetail,result,pramsNamePairs);
        if (!StringUtils.isEmpty(result)){
            JSONObject jsonObject = JSONObject.parseObject(result);
            Integer code = jsonObject.getInteger("code");
            if (code==0){
                String data = jsonObject.getString("data");
                HuiyuncheUsedCarsDTO huiyuncheUsedCarsDTO = JSONObject.parseObject(data, HuiyuncheUsedCarsDTO.class);
                UsedCarToOtm usedCarToOtm = usedCarToOtm(huiyuncheUsedCarsDTO);
                JSONObject jsonData = new JSONObject();
                jsonData.put("orderQuery", usedCarToOtm);
                String dataToOtm = jsonData.toJSONString();
                Wrapper<PushSubSystem> ew = new EntityWrapper<>();
                ew.eq("type", IntegrationURIEnum.USED_CARS.getCode());
                PushSubSystem subSystems = systemService.selectOne(ew);
                String res = HttpClientUtil.postJsoneRturnError(subSystems.getUrl(), null, dataToOtm, socketTimeout);
                JSONObject parseObject = JSONObject.parseObject(res);
                logger.info("new getOrderDetail to otm Url:{},result:{},otmParam:{}",subSystems.getUrl(),res,dataToOtm);
                //导入日志
                ImportLogHistory importLogHistory = new ImportLogHistory();
                importLogHistory.setSourceSys("hyc");
                importLogHistory.setTargetSys("OTM");
                importLogHistory.setSourceKey(huiyuncheUsedCarsDTO.getOrderCode());
                importLogHistory.setType(com.zhiche.lisa.core.enums.TableStatusEnum.STATUS_HUIYUNCHE_USEDCAR.getCode());
                if ("200".equals(parseObject.getString("messageCode"))){
                    importLogHistory.setImportStatus("success");
                }else{
                    importLogHistory.setImportStatus("error");
                }
                importLogHistory.setImportNote(res);
                importLogHistory.setImportStartTime(new Date());
                importLogHistory.setImportEndTime(new Date());
                new Thread(() -> {
                    logger.info("开始保存导入日志---------------");
                    try {
                        logService.saveImportLogToQiniu(importLogHistory, dataToOtm);
                    } catch (Exception e) {
                        logger.error("日志保存失败---------------");
                    }
                    logger.info("完成日志保存---------------");
                }).start();
            }
//            else {
//                throw new BaseException(jsonObject.getString("message"));
//            }
        }
    }


    /**
     *处理二手车推送otm数据
     */
    private UsedCarToOtm usedCarToOtm(HuiyuncheUsedCarsDTO huiyuncheUsedCarsDTO){
        SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd");
        UsedCarToOtm usedCarToOtm=new UsedCarToOtm();
        usedCarToOtm.setOrder_time(sd.format(new Date()));
        usedCarToOtm.setStd_vechile(huiyuncheUsedCarsDTO.getVehicleName());
        usedCarToOtm.setCus_vechile_des(huiyuncheUsedCarsDTO.getVehicleName());
        usedCarToOtm.setVechile_qty("1");
        usedCarToOtm.setVechile_unit("台");
        usedCarToOtm.setOrder_xid(huiyuncheUsedCarsDTO.getOrderCode());
        usedCarToOtm.setCus_order_no(huiyuncheUsedCarsDTO.getCustomerOrderCode());
        usedCarToOtm.setCus_ship_no(huiyuncheUsedCarsDTO.getCustomerOrderCode());
        usedCarToOtm.setCustomer(huiyuncheUsedCarsDTO.getCustomerName());
        usedCarToOtm.setSl_province(huiyuncheUsedCarsDTO.getDepartProvinceName());
        usedCarToOtm.setSl_city(huiyuncheUsedCarsDTO.getDepartCityName());
        usedCarToOtm.setSl_postal_code(huiyuncheUsedCarsDTO.getDepartCountyName());
        if (StringUtils.isEmpty(usedCarToOtm.getSl_postal_code())){
            usedCarToOtm.setSl_postal_code("");
        }
        usedCarToOtm.setSl_description(huiyuncheUsedCarsDTO.getDepartAddr().replace(" ",""));
        if (StringUtils.isEmpty(usedCarToOtm.getSl_description())){
            usedCarToOtm.setSl_description("");
        }
        usedCarToOtm.setSl_location_name(usedCarToOtm.getSl_province()+
                usedCarToOtm.getSl_city()+ usedCarToOtm.getSl_postal_code()+
                usedCarToOtm.getSl_description());
        usedCarToOtm.setDl_province(huiyuncheUsedCarsDTO.getReceiptProvinceName());
        usedCarToOtm.setDl_city(huiyuncheUsedCarsDTO.getReceiptCityName());
        usedCarToOtm.setDl_postal_code(huiyuncheUsedCarsDTO.getReceiptCountyName());
        if (StringUtils.isEmpty(usedCarToOtm.getDl_postal_code())){
            usedCarToOtm.setDl_postal_code("");
        }
        usedCarToOtm.setDl_description(huiyuncheUsedCarsDTO.getReceiptAddr().replace(" ",""));
        if (StringUtils.isEmpty(usedCarToOtm.getDl_description())){
            usedCarToOtm.setDl_description("");
        }
        usedCarToOtm.setDl_location_name(usedCarToOtm.getDl_province()+
                usedCarToOtm.getDl_city()+ usedCarToOtm.getDl_postal_code()+
                usedCarToOtm.getDl_description());
        usedCarToOtm.setOrder_model(huiyuncheUsedCarsDTO.getVehicleName());
        usedCarToOtm.setVin(huiyuncheUsedCarsDTO.getVin());
        usedCarToOtm.setEtd(sd.format(huiyuncheUsedCarsDTO.getDeliveryDate()));
        if (Objects.nonNull(huiyuncheUsedCarsDTO.getArriveDate()))
        usedCarToOtm.setEta(sd.format(huiyuncheUsedCarsDTO.getArriveDate()));
        usedCarToOtm.setOt__ar_miles(huiyuncheUsedCarsDTO.getDistance());
        if (Objects.isNull(usedCarToOtm.getOt__ar_miles())){
            usedCarToOtm.setOt__ar_miles(BigDecimal.ZERO);
        }
        usedCarToOtm.setFixed_price(huiyuncheUsedCarsDTO.getCost());
        if (huiyuncheUsedCarsDTO.getIsCash()==1){
            usedCarToOtm.setCost_type("现金");
            usedCarToOtm.setInvoice("不开票");
        }else if(huiyuncheUsedCarsDTO.getIsCash()==0){
            usedCarToOtm.setCost_type("不是现金");
            usedCarToOtm.setInvoice("开票");
        }
        return usedCarToOtm;
    }
}